package com.jessechanrui.template.skeleton.interfaces.validated.http;

import com.jessechanrui.template.shardingsphere.validated.dto.UserDTO;
import com.jessechanrui.template.shardingsphere.validated.dto.ValidatedDTO;
import com.jessechanrui.template.shardingsphere.validated.dto.ValidationList;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Email;

/**
 * 参数校验测试
 *  参数平铺到方法入参中。在这种情况下，必须在Controller类上标注@Validated注解
 *  给DTO对象加上@Validated或者@Valid注解就能实现自动参数校验
 *
 * @author chenrui
 * @date 2024/2/29
 */
@RestController
@RequestMapping("/validated")
@Api("参数校验测试")
@Validated
@Slf4j
public class ValidatedController {

    @GetMapping("/common")
    @ApiOperation("测试@valid验证单个值参数校验")
    public String commonValid(@RequestParam(name = "email") @Email String email){
        log.info("邮箱地址:" + email);
        return email;
    }

    /**
     *
     * @param validatedDTO
     * @return
     */
    @PostMapping("/dto")
    @ApiOperation("测试@valid验证对象值参数校验")
    public ValidatedDTO dtoValidated(@RequestBody @Valid ValidatedDTO validatedDTO) {
        log.info("对象参数值:" + validatedDTO.toString());
        return validatedDTO;
    }

    @PostMapping("/save")
    @ApiOperation("测试保存分组校验")
    public ValidatedDTO saveValidate(@RequestBody @Validated(ValidatedDTO.Save.class) ValidatedDTO validatedDTO) {
        log.info("对象参数值:" + validatedDTO.toString());
        return validatedDTO;
    }

    @PostMapping("/update")
    @ApiOperation("测试更新分组校验")
    public ValidatedDTO updateValidate(@RequestBody @Validated(ValidatedDTO.Update.class) ValidatedDTO validatedDTO) {
        log.info("对象参数值:" + validatedDTO.toString());
        return validatedDTO;
    }

    @PostMapping("/nested/save")
    @ApiOperation("测试保存分组嵌套校验")
    public UserDTO saveNestedValidate(@RequestBody @Validated(UserDTO.Save.class) UserDTO userDTO) {
        log.info("对象参数值:" + userDTO.toString());
        return userDTO;
    }

    @PostMapping("/nested/update")
    @ApiOperation("测试更新分组嵌套校验")
    public UserDTO updateNestedValidate(@RequestBody @Validated(UserDTO.Update.class) UserDTO userDTO) {
        log.info("对象参数值:" + userDTO.toString());
        return userDTO;
    }

    @PostMapping("/saveList")
    @ApiOperation("测试集合校验")
    public ValidationList<UserDTO> saveList(@RequestBody @Validated(UserDTO.Save.class) ValidationList<UserDTO> userList) {
        // 校验通过，才会执行业务逻辑处理
        if(userList != null){
            for(UserDTO userDTO : userList){
                log.info(userDTO.toString());
            }
        }
        return userList;
    }
}
